package com.itheima.service.mongo.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.RandomUtil;
import com.itheima.domain.mongo.RecommendVideo;
import com.itheima.domain.mongo.Video;
import com.itheima.service.mongo.VideoService;
import com.itheima.util.ConstantUtil;
import com.itheima.vo.PageBeanVo;
import org.apache.dubbo.config.annotation.DubboService;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.ArrayList;
import java.util.List;

@DubboService
public class VideoServiceImpl implements VideoService {

    @Autowired
    MongoTemplate mongoTemplate;

    @Autowired
    RedisIdService redisIdService;

    @Override
    public PageBeanVo findRecommendVideoByPage(Long userId, Integer pageNum, Integer pageSize) {
        //1.创建条件对象(推荐人,分页,排序)
        Query query = new Query(Criteria.where("userId").is(userId))
                .with(Sort.by(Sort.Order.desc("date")))
                .skip((pageNum-1)*pageSize).limit(pageSize);

        //2.查询推荐视频表,返回list
        List<RecommendVideo> recommendVideos = mongoTemplate.find(query, RecommendVideo.class);

        //3.遍历推荐list,获取每个视频的id,查询视频详情,放入video集合中
        List<Video> videoList = new ArrayList<>();

        if (CollUtil.isNotEmpty(recommendVideos)) {
            for (RecommendVideo recommendVideo : recommendVideos) {
                ObjectId videoId = recommendVideo.getVideoId();
                Video video = mongoTemplate.findById(videoId, Video.class);

                videoList.add(video);
            }
        }
        //4.封装pageBeanVo返回
        Long counts = Long.valueOf(videoList.size());
        return new PageBeanVo(pageNum,pageSize,counts,videoList);
    }

    @Override
    public void save(Video video) {
        //0.给video设置vid
        video.setVid(redisIdService.getNextId(ConstantUtil.VIDEO_ID));

        //1.保存到video表中
        mongoTemplate.save(video);

        //2.封装推荐视频对象
        RecommendVideo recommendVideo = new RecommendVideo();
        recommendVideo.setDate(video.getCreated());
        recommendVideo.setVid(video.getVid());
        recommendVideo.setUserId(video.getUserId());
        recommendVideo.setVideoId(video.getId());
        recommendVideo.setScore(RandomUtil.randomDouble(90.99));

        //3.存放到推荐视频表中
        mongoTemplate.save(recommendVideo);
    }
}
